import urllib

from django import template
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils.hashcompat import md5_constructor

from idit.settings import AVATAR_DEFAULT_URL, AVATAR_GRAVATAR_DEFAULT

register = template.Library()

def avatar_url(user, size=80):
    if not isinstance(user, User):
        try:
            user = User.objects.get(username=user)
        except User.DoesNotExist:
            return AVATAR_DEFAULT_URL
    params = {'s': str(size)}
    if AVATAR_GRAVATAR_DEFAULT:
        params['d'] = AVATAR_GRAVATAR_DEFAULT
    return "http://www.gravatar.com/avatar/%s/?%s" % (md5_constructor(user.email).hexdigest(),urllib.urlencode(params))
register.simple_tag(avatar_url)

def avatar(user, size=80):
    if not isinstance(user, User):
        try:
            user = User.objects.get(username=user)
            alt = unicode(user)
            url = avatar_url(user, size)
        except User.DoesNotExist:
            url = AVATAR_DEFAULT_URL
            alt = _("Default Avatar")
    else:
        alt = unicode(user)
        url = avatar_url(user, size)
    return """<img src="%s" alt="%s" width="%s" height="%s" />""" % (url, alt,
        size, size)
register.simple_tag(avatar)
